<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\Admin;

class Login extends Controller
{
    /**
     * 管理员登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return json
     */
    public function login()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Admin');
        if (!$validate->scene('login')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $admin = Admin::where('username', $data['username'])->find();
        if (!$admin || !password_verify($data['password'], $admin->password)) {
            return json(['code' => 0, 'msg' => '用户名或密码错误']);
        }

        session('admin_id', $admin->id);
        session('admin_name', $admin->username);
        
        return json(['code' => 1, 'msg' => '登录成功']);
    }

    /**
     * 退出登录
     * @return json
     */
    public function logout()
    {
        session(null);
        return json(['code' => 1, 'msg' => '退出成功']);
    }
} 